﻿
CREATE OR REPLACE FUNCTION fn_check_constraint_project_budget(p_order_id integer,p_product_id integer)
  RETURNS boolean AS
$BODY$
declare
	prj_id2 integer;
	chk_c boolean;
begin
	Select into prj_id2 project_id from purchase_order where id=$1;
	if exists(Select kbd.id from kdvn_budget_data kbd left join product_product pp on kbd.budget_id = pp.kdvn_budget_id where project_id=prj_id2 and pp.id=$2) then
		chk_c = true;
	else
		chk_c = false;
	end if;
	return chk_c;
end;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
-- 
--Select * from kdvn_project where id=175;
--Select project_id from purchase_order where id=4140;;
--Select * from kdvn_budget_data where project_id=175 and budget_id=277;
--Select kdvn_budget_id from product_product where id=1707
--delete  from "BudgetNewCode" ;
--Select fn_check_constraint_project_budget(4143,Null,1707);
--Select * from "BudgetNewCode" 

--Check 
Select name from purchase_order where id in (
 Select distinct
	order_id
from 
	purchase_order_line pol
left join
	purchase_order po on order_id = po.id
left join 
	product_product pp on pol.product_id=pp.id 
left join 
	kdvn_budget_data kbd on pol.project_id=kbd.project_id and budget_id=kdvn_budget_id where coalesce(kbd.id,0)=0)
